package com.tools.api;

import com.amazonaws.util.IOUtils;
import com.tools.commons.annotation.AnonymousAccess;
import com.tools.commons.constants.SystemConstants;
import com.tools.commons.response.ResponseCode;
import com.tools.model.entity.PicsEntity;
import com.tools.service.PicService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

@RestController
@RequiredArgsConstructor
public class PicController {

    private final PicService picService;

    @PostMapping(SystemConstants.Api.PICS)
    @AnonymousAccess
    private List<PicsEntity> uploadPics(@RequestParam("files") MultipartFile files) {


        return picService.upload(files);
    }

    @GetMapping(value = "/pics/{ossKey}.png")
    @AnonymousAccess
    public void getFileByOssKey(@PathVariable String ossKey, HttpServletResponse response) {
        writeImageToResponse(picService.getUrl(ossKey), response);
    }

    private void writeImageToResponse(String imageUrl, HttpServletResponse response) {
        try {
            OutputStream out = response.getOutputStream();
            URL url = new URL(imageUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            IOUtils.copy(conn.getInputStream(), out);
            response.setHeader("Content-Type", "image/jpeg");
        } catch (IOException e) {
            ResponseCode.BAD_REQUEST.throwException("服务器错误");
        }
    }
}
